#!/usr/bin/python

import commands
import os
import sys
import datetime
import urllib
import re
from optparse import OptionParser

from movie.vote.models import Movie

MOVIE_SEARCH_BIN = './movie-search'

def UpdateMovieTrailers(days_back):
  if not days_back:
    movies = Movie.objects.all()
  else:
    cutoff = datetime.datetime.now() - datetime.timedelta(days_back)
    movies = Movie.objects.filter(date_added__gt=cutoff)
  for movie in movies:
    if movie.youtube_trailer_url:
      continue
    url = commands.getoutput('%s --trailer "%s"' % (MOVIE_SEARCH_BIN, movie.name))
    if not url.startswith('http'):
      continue
    print 'Adding trailer for %s: %s' % (movie.name, url)
    movie.youtube_trailer_url = url
    movie.save()
  

if __name__ == '__main__':
  usage = "usage: %prog [options]"
  parser = OptionParser(usage)
  parser.add_option('-d', '--days_back', type='int', dest='days_back', default=5,
                    help='skip movies older than this many days')
  (options, args) = parser.parse_args()
  UpdateMovieTrailers(days_back=options.days_back)
